package com.inspinia.base.util; /**
 * Copyright lenovo-cw.com 2013. All rights reserved.
 *
 * @createDate 2013-2-16
 */


import com.inspinia.base.util.properties.HttpConfig;
import org.apache.http.HttpEntity;
import org.apache.http.client.params.AllClientPNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * http客户端连接池
 *
 * @author fengwx
 * @date 2013-3-4
 */
public class HttpClientPool {

    public static final int CONNECTION_TIMEOUT = Integer.parseInt(HttpConfig.connectionTime);
    public static final int READ_TIMEOUT = Integer.parseInt(HttpConfig.readTimeout);

    private static ThreadSafeClientConnManager cm = null;

    static {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(
                new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(
                new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

        cm = new ThreadSafeClientConnManager(schemeRegistry);
        // Increase max total connection to 200
        cm.setMaxTotal(100);
        // Increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);
    }

    /**
     * 从连接池中获取HttpClient
     */
    public static DefaultHttpClient getHttpClient() {
        return getHttpClient(CONNECTION_TIMEOUT, READ_TIMEOUT);
    }

    /**
     * 从连接池中获取HttpClient
     *
     * @param connectTimeout 连接超时
     * @param readTimeout    读取超时
     * @return
     */
    public static DefaultHttpClient getHttpClient(int connectTimeout, int readTimeout) {
        DefaultHttpClient httpClient = new DefaultHttpClient(cm);
        // 设置 连接超时时间
        httpClient.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, connectTimeout);
        // 设置 读数据超时时间
        httpClient.getParams().setParameter(AllClientPNames.SO_TIMEOUT, readTimeout);

        return httpClient;
    }

    /**
     * 释放连接
     */
    public static void consume(HttpEntity entity) {
        try {
            EntityUtils.consume(entity);
        } catch (IOException e) {
        }
    }

}

